package recallin.social.facebook;

import org.json.JSONException;
import org.json.JSONObject;

import recallin.activities.MainActivity;
import recallin.social.facebook.SessionEvents.AuthListener;
import recallin.social.facebook.SessionEvents.LogoutListener;
import android.R.layout;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.R;

public class FacebookDialog extends Dialog {

	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;

	private final String[] main_items = { "Check in", "Logout" };

	private ImageView mUserPic;
	private TextView mUserName;

	private FacebookHandler facebookHandler;

	private SessionListener mSessionListener = new SessionListener();

	public FacebookDialog(Context context) {
		super(context);
		this.getWindow().setGravity(Gravity.TOP);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		SessionEvents.addAuthListener(mSessionListener);
		SessionEvents.addLogoutListener(mSessionListener);

		
		facebookHandler = new FacebookHandler();
		facebookHandler.sendEmptyMessage(FacebookHandler.VALIDATE);

		this.setContentView(R.layout.facebook_dialog);
		
		mUserPic = (ImageView) this.findViewById(R.id.facebook_dialog_user_pic);
		mUserName = (TextView) this.findViewById(R.id.facebook_dialog_txt);
		
		requestUserData();
		



		ListView menuList = (ListView) this
				.findViewById(R.id.facebook_dialog_menu_list);
		menuList.setAdapter(new ArrayAdapter<String>(getContext(),
				layout.simple_list_item_1, main_items));
		menuList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				switch (position) {
				case 0:
					hide();
					new Places(getContext(), FacebookDialog.this).show();
					break;
				case 1:
					if (Utility.mFacebook.isSessionValid()) {
			            SessionEvents.onLogoutBegin();
			            AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
			            asyncRunner.logout(getContext(), new LogoutRequestListener());
			        } else {
			            Utility.mFacebook.authorize(getOwnerActivity(), MainActivity.PERMISSIONS, MainActivity.AUTHORIZE_ACTIVITY_RESULT_CODE, new LoginDialogListener());
			        }
					break;
				default:
					break;
				}
			}
		});

	}
	
	class FacebookHandler extends Handler {
		private static final int VALIDATE = 0;

		@Override
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch (what) {
			case VALIDATE:
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	/*
	 * Request user name, and picture to show on the main screen.
	 */
	public void requestUserData() {
		mUserName.setTextSize(15);
		mUserName.setText("Fetching user data..");
		Bundle params = new Bundle();
		params.putString("fields", "name, picture");
		Utility.mAsyncRunner.request("me", params, new UserRequestListener());
	}

	/*
	 * Callback for fetching current user's name, picture, uid.
	 */
	public class UserRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

				final String picURL = jsonObject.getString("picture");
				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");

				facebookHandler.post(new Runnable() {
					@Override
					public void run() {
						mUserName.setTextSize(23);
						mUserName.setText(name);
						mUserPic.setImageBitmap(Utility.getBitmap(picURL));
					}
				});

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	public class LogoutRequestListener extends BaseRequestListener {
		@Override
		public void onComplete(String response, Object state) {
			SessionEvents.onLogoutFinish();
		}
	}
	
	public class LoginDialogListener implements DialogListener {
        @Override
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        @Override
        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        @Override
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        @Override
        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
	
	private class SessionListener implements AuthListener, LogoutListener {

        @Override
        public void onAuthSucceed() {
            SessionStore.save(Utility.mFacebook, getContext());
        }

        @Override
        public void onAuthFail(String error) {
        }

        @Override
        public void onLogoutBegin() {
        }

        @Override
        public void onLogoutFinish() {
        	dismiss();
            SessionStore.clear(getContext());
        }
    }
	
}
